<template>
  <div>
    <zm-panel :title="Title" :visible.sync="value" @change="close">
      <div>
        <el-tabs v-model="editableTabsValue">
          <el-tab-pane label="基本信息" name="1">
            <step-one
              ref="step1"
              v-model="form"
              :my-customer-list="myCustomerList"
              @new-customer="goNewCustomer"
            ></step-one>
          </el-tab-pane>
          <el-tab-pane :label="labelName" name="2">
            <step-book ref="stepBook" :rule="form.bookRule" v-if="!loading && form.type === '4'" @after-change="bookChange"></step-book>
            <step-goods ref="stepGoods" :rule="form.productList" v-else-if="!loading && form.type === '6'" @after-change="GoodsChange"></step-goods>
            <step-wen ref="stepWen" :rule="form.wenlvRule" v-else-if="!loading && form.type === '7'" @after-change="wenlvChange"></step-wen>
            <step-two ref="step2" v-model="form" v-else></step-two>
          </el-tab-pane>
           <el-tab-pane label="选择送券" name="3" v-if="['1', '2', '3'].includes(form.type) && !loading">
             <send-stamps :row-info="rowInfo" :rule="form" @selectId="selectId"></send-stamps>
        </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="tr">
        <zm-button @click="close" type="">取 消</zm-button>
        <zm-button @click="prev" v-if="+editableTabsValue !== 1" type="">
          上一步
        </zm-button>
        <zm-button @click="next" v-if="['4','5','6','7'].includes(form.type) && +editableTabsValue === 1" type="primary">
          下一步
        </zm-button>
        <zm-button @click="next" v-if="['1', '2','3'].includes(form.type) && [1,2,3].includes(+editableTabsValue)" type="primary">
          下一步
        </zm-button>
        <zm-button @click="save" v-if="(+editableTabsValue === 2 && ['4','5','6','7'].includes(form.type)) || (+editableTabsValue === 3 && ['1', '2', '3'].includes(form.type))" type="primary">
          保存订单
        </zm-button>
        <!-- 从审批进入编辑时无需提交审批 -->
        <zm-button
          @click="save('submitAppro')"
          v-if="((+editableTabsValue === 2 && ['4','5','6','7'].includes(form.type)) || (+editableTabsValue === 3 && ['1', '2', '3'].includes(form.type))) && $route.name !== 'approvalMgr'"
          type="primary"
        >
          提交审批
        </zm-button>
      </div>
    </zm-panel>
    <new-customer
      v-if="customerVisible"
      v-model="customerVisible"
      @after="getCustomerList"
    ></new-customer>
  </div>
</template>
<script>
import panelMixin from '@/mixins/panelMixin'
import StepOne from './StepOne'
import StepTwo from './StepTwo'
import StepBook from './StepBook'
import StepGoods from './StepGoods'
import StepWen from './StepWen.vue'
import saleOrderApi from '@/api/src/saleOrder'
import approveProcessApis from '@/api/src/approve'
import customerApis from '@/api/src/customer'
import NewCustomer from '@/views/customer/customerList/components/New'
import SendStamps from './SendStamps.vue'

export default {
  components: { StepOne, StepTwo, StepBook, StepGoods, NewCustomer, SendStamps, StepWen },
  mixins: [panelMixin],
  props: {
    rowInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      editableTabsValue: '1',
      stepList: ['基本信息', '销售产品'],
      myCustomerList: [],
      customerVisible: false,
      form: {
        type: '', // 1日常，2特殊，3客情, 4 包场, 5 客诉
        name: '',
        contractType: '',
        customerId: '',
        companyType: '',
        settlementType: '1',
        enclosureUrl: '',
        enclosureUrlName: '',
        signDate: '',
        isInvoice: '1',
        invoiceContent: '',
        invoiceType: '',
        companyId: '',
        companyName: '',
        companyObj: {
          companyId: '',
          companyName: ''
        },
        complaintType: '', // 客诉所属字段
        complaintRemark: '', // 客诉所属字段
        businessScene: '', // 客情销售单业务场景
        // 第二步
        productId: '',
        productName: '',
        couponProductId: '',
        saleType: '',
        salePrice: '',
        couponPrice: '',
        couponNumber: '',
        parValue: '',
        number: '',
        saleTotalPrice: '',
        computedTotal: '',
        expiredType: '1',
        isGive: '0',
        isUnbundling: '0',
        isCashDiff: '0', // 销售单是否开发现金补差
        isOpenRecharge: '0',
        startDate: '',
        endDate: '',
        endComputedDate: '',
        floatDay: '',
        floatUnit: 'day',
        remark: '',
        saleScalePrice: '',
        saleScalePoint: '',
        consumptionScalePrice: '',
        consumptionScalePoint: '',
        isCustomize: '0',
        cikaSalePrice: '',
        customizePrice: [
          {
            unitPrice: '',
            unitPoint: '',
            num: '',
            totalPrice: ''
          }
        ],
        proportion: '',
        theoryCostPrice: '', // 理论成本
        practiceCostPrice: '', // 实际成本
        cardSaleScale: '', // 销售折扣
        minSalPrice: '', // 最低销售单价 包场单中使用
        ruleProportion: '', // 提成比例 包场单中使用
        bookRule: { // 包场规则
          cinemaData: {
            relationType: '2',
            relationId: ''
          },
          rule: [{
            filmName: '',
            hallRemark: '',
            startDate: '',
            endDate: ''
          }]
        },
        productList: { // 实物销售单 文旅销售单
          totalPrice: '0',
          list: [
            /* {
              productId: '', // 商品ID
              minSalePrice: '', // 最低销售单价
              deliveryMoney: '', // 运费
              name: '', //  商品名
              price: '', // 单价
              number: '' // 数量
            } */
          ]
        },
        wenlvRule: {
          totalPrice: '0',
          list: [
            {
              type: '1', // 活动类型 1党建 2春秋游 3体育赛事 4其他
              address: '', // 活动场地
              startTime: '', // 活动开始时间
              endTime: '', //  活动结束时间
              calculationMethod: '1', // 销售总额计算方式 1按人头算 2按场次算
              unitPrice: '', // 销售单价
              joinCount: '', // 活动人数
              totalSalePrice: '', //  销售总额
              remark: '' // 活动备注
            }
          ]
        },
        // 第三步
        isSendProgram: '',
        cardPlan: '',
        types: ''
      },
      loading: false
    }
  },
  computed: {
    Title () {
      return this.rowInfo.id ? '编辑销售单' : '新增销售单'
    },
    labelName () {
      return this.form.type === '4' ? '包场规则' : this.form.type === '7' ? '活动规则' : '销售产品'
    },
    processType () {
      let num
      if (+this.form.type <= 3) {
        num = +this.form.type + 2
      } else if (+this.form.type === 4) {
        num = 9
      } else if (+this.form.type === 5) {
        num = 10
      } else if (+this.form.type === 6) {
        num = 12
      } else if (+this.form.type === 7) {
        num = 13 // 文旅
      }
      return num
    }
  },
  watch: {},
  created () {
    this.init()
    this.$set(this.form, 'type', this.rowInfo.type + '')
  },
  methods: {
    // 被选择的id
    selectId (selectId) {
      // this.form = {...this.form, sendProgramId: selectId}
    },
    // 获取客户列表
    async getCustomerList () {
      const _res = await customerApis.getMyCustomerList({
        orderId: this.form.id
      })
      this.myCustomerList = _res
    },
    goNewCustomer () {
      this.customerVisible = true
    },
    // 获取详情
    async init () {
      this.loading = true
      if (this.rowInfo.id) {
        const _res = await saleOrderApi.getInfo({ id: this.rowInfo.id })

        this.form = {
          ...this.form,
          ..._res,
          customizePrice:
            _res.customizePrice && JSON.parse(_res.customizePrice),
          endComputedDate: _res.endDate,
          companyObj: {
            companyId: _res.companyId,
            companyName: _res.companyName
          }
        }
        if (this.form.computedTotal !== +this.form.saleTotalPrice) {
          this.$set(this.form, 'computedTotal', _res.saleTotalPrice)
        }
        if (this.form.productType === '4') {
          this.$refs.step2.getFrequencyCardProductList({
            productId: this.form.productId
          })
          this.form.cikaSalePrice =
            +this.form.couponNumber * +this.form.couponPrice || '--'
        }
        if (this.form.type === '6') {
          this.form.productList = JSON.parse(this.form.productList)
        }
      }
      this.getCustomerList()
      this.$nextTick(() => {
        this.loading = false
      })
    },
    // 下一步
    next () {
      // 优惠券特殊处理
      this.$refs[`step${this.editableTabsValue}`]
        .handleFormValidate()
        .then(() => {
          this.editableTabsValue = (+this.editableTabsValue + 1).toString()
        })
        .catch(err => err)
    },
    // 上一步
    prev () {
      this.editableTabsValue = (+this.editableTabsValue - 1).toString()
    },
    goSuccess () {
      this.$emit('after-save', true)
      this.$message.success('操作成功')
      this.close()
    },
    // 完成
    async save (buttonType) {
      const step1 = this.$refs.step1.handleFormValidate()
      const step2 = this.$refs.step2 && this.$refs.step2.handleFormValidate()
      try {
        await Promise.all([step1, step2])
      } catch (err) {
        this.$message.warning(`${err}有未填项，请填写完整`)
        return
      }
      // v1.1.0 超出产品配置时间范围 2/3/4/5类型不需要进行时间范围判断
      const timeArea = (new Date(this.form.endDate) - new Date(this.form.startDate)) / 3600 / 24 / 1000 + 1
      const _type = ['2', '3', '4', '5']
      if (!_type.includes(this.form.type) && this.form.endDate && +timeArea > +this.form.productExpiredDays) {
        this.$message.error('有效期超出产品配置的有效期范围')
        return
      }

      // v1.1.0 日常销售单的 销售单总额 不能超过 客户类型中配置的日常销售总额
      if (this.form.type === '1' && +this.form.computedTotal > +this.form.rental) {
        this.$message.error('销售单总额超出配置，请去填写特价单')
        return
      }

      const _res = this.isTruePrice()
      if (_res) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.7)'
        })
        await this.submitApi(buttonType)
        loading.close()
      } else {
        return
      }
      this.goSuccess()
    },
    isTruePrice () {
      let costPrice =
        this.form.practiceCostPrice && this.form.practiceCostPrice !== '0.00'
          ? +this.form.practiceCostPrice
          : +this.form.theoryCostPrice
      let isFalse
      if (this.form.productType === '3' && this.form.isCustomize === '1') {
        // 点卡自定义
        let ride = this.form.customizePrice.map(i => {
          return +i.unitPrice * +i.num
        })
        let rideTotal = ride.reduce((n, m) => n + m)
        let total = this.form.customizePrice.map(i => +i.totalPrice)
        let totalPrice = total.reduce((n, m) => n + m)
        let scale = (totalPrice / rideTotal) * 100
        isFalse = scale < costPrice
      } else if (
        this.form.productType === '3' &&
        this.form.isCustomize === '0'
      ) {
        // 点卡统一金额
        let result =
          (+this.form.computedTotal /
            (+this.form.salePrice * +this.form.number)) *
          100
        isFalse = result < costPrice
      } else if (this.form.productType === '4') {
        isFalse = +this.form.couponPrice < costPrice
      } else {
        isFalse = +this.form.salePrice < costPrice
      }
      if (this.form.type === '1' && isFalse) {
        this.$confirm(
          '销售单价低于成本价，无法提交，是否变更特殊申请单进行提交',
          '提示',
          {
            confirmButtonText: '变更',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.$set(this.form, 'startDate', '')
            this.$set(this.form, 'type', '2')
            return false
          })
          .catch(() => {
            return false
          })
      } else {
        return true
      }
    },
    // stepBook
    bookChange (val) {
      this.form.bookRule = val
      /* this.form.bookRule.map(i => {
        i.cinemaType = i.cinemaData.cinemaType
        i.cinemaId = i.cinemaData.cinemaId
      }) */
    },
    // stepGoods
    GoodsChange (val) {

    },
    // wenlv
    wenlvChange (val) {

    },
    async submitApi (buttonType) {
      // 保存接口
      const _saleTotalPrice = this.form.type !== '4' ? this.form.computedTotal : this.form.saleTotalPrice
      // 次卡类型的 salePrice 取 cikaSalePrice 字段
      this.form.salePrice = this.form.productType === '4' ? this.form.cikaSalePrice : this.form.salePrice
      let params = {
        ...this.form,
        saleTotalPrice: _saleTotalPrice,
        /* endDate:
          this.form.type === '1' && this.form.expiredType === '1'
            ? this.form.endComputedDate
            : this.form.endDate, */
        floatDay:
          this.form.type === '1' && this.form.expiredType === '2'
            ? this.form.productExpiredDays
            : this.form.floatDay
      }
      console.log(params, 'MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM')
      if (this.rowInfo.id && buttonType !== 'submitAppro') {
        return saleOrderApi.update({
          ...params,
          id: this.rowInfo.id,
          isApprove: this.rowInfo.isApprove
        })
      } else if (buttonType === 'submitAppro') {
        // 提交审批前检测
        await approveProcessApis.checkApprove({
          processType: this.processType
        })
        const res = this.rowInfo.id
          ? await saleOrderApi.update({
            ...params,
            id: this.rowInfo.id,
            isApprove: this.rowInfo.isApprove
          })
          : await saleOrderApi.create(params)
        return approveProcessApis.submit({
          processType: this.processType,
          linkName: this.form.name,
          businessId: res.id
        })
      } else {
        return saleOrderApi.create(params)
      }
    }
  }
}
</script>
